package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.Channel;
import com.rockcent.mall.lib.domain.enumclass.ChannelClientType;
import com.rockcent.mall.lib.domain.enumclass.ChannelStatus;
import com.rockcent.mall.lib.dto.ChannelEventDto;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.dto.ProductDto;
import com.rockcent.mall.lib.repository.ChannelRepository;
import com.rockcent.mall.lib.repository.MerchantProductRepository;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.ChannelHelper;
import com.rockcent.wechat.helper.CustomerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by HK on 16/9/28.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class MerchantChannelController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(MerchantChannelController.class);

    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private CustomerHelper customerHelper;
    @Autowired
    private ChannelHelper channelHelper;

    /**
     * @api {get} /api/v2/channel/product_show 查询渠道产品列表
     * @apiGroup channel
     * @apiVersion 1.0.0
     * @apiParam {Long} channelId 渠道ID
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiSuccess {String} id 渠道ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 渠道名称
     * @apiSuccess {Long} channelTypeId 类型
     * @apiSuccess {String} flowEstimation 流量估计
     * @apiSuccess {String} intro 渠道简介
     * @apiSuccess {String} detail 渠道描述
     * @apiSuccess {Long} merchantId 商户id
     * @apiSuccess {Long} saleCount 销售量
     * @apiSuccess {Long} verifiedCount 核销量
     * @apiSuccess {Long} productCount 上架产品数
     * @apiSuccess {Boolean} systemDefault 是否默认渠道
     * @apiSuccess {List} productList 产品列表
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} type 类型 ALL("全部"), GOODS("商品"), SERVICE("服务")
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 售价
     * @apiSuccess {Long} quantity  库存数量
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {Boolean} refundable 是否支持过期退
     * @apiSuccess {Boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String} status 状态 SELLING("在售"), SUPPLIER_CANCEL_SOLDOUT("分销市场 供应商取消供货 已下架"),DISTRIBUTOR_CANCEL_SOLDOUT("分销市场 分销商取消代销 已下架"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} channelSalesCode 渠道码
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {Boolean} recommend 是否在分销市场展示
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "data": [
     * {
     * "id": 999,
     * "dateCreated": "2016-11-13 14:46:16",
     * "lastUpdated": "2016-11-15 11:40:17",
     * "version": 5,
     * "marketMerchantName": "6666",
     * "name": "自营物流产品001",
     * "type": "GOODS",
     * "basePrice": 100,
     * "sellPrice": 90,
     * "quantity": 10,
     * "carriage": 0,
     * "refundable": false,
     * "barcode": "",
     * "sellnow": true,
     * "dateSelling": "2016-11-13 14:46:16",
     * "limitCount": 0,
     * "logoUrl": "http://uploads.rockcent.com//uat/product/face/201611/13144673691dcbd4d4-767a-475b-8efc-b9f9b0aa494c5243fbf2b2119313e3f2c41261380cd790238dda.jpg",
     * "logoUrls": "[\"http://uploads.rockcent.com//uat/product/face/201611/13144673691dcbd4d4-767a-475b-8efc-b9f9b0aa494c5243fbf2b2119313e3f2c41261380cd790238dda.jpg\"]",
     * "note": "111111111111",
     * "status": "SELLING",
     * "channelSalesCode": "24235345",
     * "mallId": 1,
     * "merchantId": 74,
     * "merchantName": "改名了6666",
     * "serveRate": "2.5",
     * "resellFee": 15,
     * "shareFee": 8,
     * "recommend": false
     * },
     * ...
     * ],
     * "totalCount": 9,
     * "totalPage": 1,
     * "pageNo": 0,
     * "pageSize": 10
     * }
     * }
     */
    @RequestMapping(value = Routes.CHANNEL_PRODUCT_SHOW, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult show(Long channelId, Integer pageNo, Integer pageSize, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (pageNo == null || pageSize == null) {
                jr.remind("请输入分页条件",log);
                return;
            }
            if (channelId == null) {
                jr.remind("渠道为空",log);
                return;
            }
            Channel channel = channelRepository.findByIdAndIsDeleteAndChannelStatus(channelId, Whether.NO, ChannelStatus.USING);
            if (channel == null) {
                jr.errorParam("该渠道已经停用",log);
                return;
            }
            PageResult<ProductDto> productPageResult = merchantProductRepository.getChannelProduct(channelId, this.getPage(pageNo, pageSize));
            jr.setData(productPageResult);

            //新增渠道访问数
            ChannelEventDto channelEvent = new ChannelEventDto();
            channelEvent.setChannelId(channel.getId());
            channelEvent.setMallId(channel.getMallId());
            channelEvent.setMerchantId(channel.getMerchantId());
            channelEvent.setVisitIp(RequestUtils.getIpAddress(request));
            channelEvent.setVisitCustomerId(customerDto.getId());
            channelHelper.addChannelViewLog(channelEvent);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/channel/get 查询渠道信息
     * @apiGroup channel
     * @apiVersion 1.0.0
     * @apiParam {Long} channelId 渠道ID
     * @apiSuccess {String} id 渠道ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 渠道名称
     * @apiSuccess {Long} channelTypeId 类型
     * @apiSuccess {String} flowEstimation 流量估计
     * @apiSuccess {String} intro 渠道简介
     * @apiSuccess {String} detail 渠道描述
     * @apiSuccess {Long} merchantId 商户id
     * @apiSuccess {Long} saleCount 销售量
     * @apiSuccess {Long} verifiedCount 核销量
     * @apiSuccess {Long} productCount 上架产品数
     * @apiSuccess {Boolean} systemDefault 是否默认渠道
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "id": 5,
     * "dateCreated": "2016-07-28 16:13:40",
     * "lastUpdated": "2016-11-07 11:45:19",
     * "version": 0,
     * "name": "默认自有渠道",
     * "channelTypeId": 14,
     * "flowEstimation": "未知",
     * "intro": "系统创建默认自有渠道",
     * "detail": "系统创建默认自有渠道",
     * "number": "001",
     * "channelStatus": "USING",
     * "merchantId": 2,
     * "systemDefault": true
     * }
     * }
     */
    @RequestMapping(value = Routes.CHANNEL_GET, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getChannel(Long channelId, HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (channelId == null) {
                jr.remind("渠道为空",log);
                return;
            }
            Channel channel = channelRepository.findByIdAndIsDeleteAndChannelStatus(channelId, Whether.NO, ChannelStatus.USING);
            if (channel == null) {
                jr.errorParam("该渠道已经停用",log);
                return;
            }
            jr.setData(channel);
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /api/v2/channel/wxapp_product/list 小程序 查询渠道产品列表
     * @apiGroup channel
     * @apiVersion 1.0.0
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiParam {Long} channelId 渠道ID
     *
     * @apiSuccess {String} id 渠道ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 渠道名称
     * @apiSuccess {Long} channelTypeId 类型
     * @apiSuccess {String} flowEstimation 流量估计
     * @apiSuccess {String} intro 渠道简介
     * @apiSuccess {String} detail 渠道描述
     * @apiSuccess {Long} merchantId 商户id
     * @apiSuccess {Long} saleCount 销售量
     * @apiSuccess {Long} verifiedCount 核销量
     * @apiSuccess {Long} productCount 上架产品数
     * @apiSuccess {Boolean} systemDefault 是否默认渠道
     * @apiSuccess {List} productList 产品列表
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} type 类型 ALL("全部"), GOODS("商品"), SERVICE("服务")
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 售价
     * @apiSuccess {Long} quantity  库存数量
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {Boolean} refundable 是否支持过期退
     * @apiSuccess {Boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String} status 状态 SELLING("在售"), SUPPLIER_CANCEL_SOLDOUT("分销市场 供应商取消供货 已下架"),DISTRIBUTOR_CANCEL_SOLDOUT("分销市场 分销商取消代销 已下架"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} channelSalesCode 渠道码
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {Boolean} recommend 是否在分销市场展示
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "data": [
     * {
     * "id": 999,
     * "dateCreated": "2016-11-13 14:46:16",
     * "lastUpdated": "2016-11-15 11:40:17",
     * "version": 5,
     * "marketMerchantName": "6666",
     * "name": "自营物流产品001",
     * "type": "GOODS",
     * "basePrice": 100,
     * "sellPrice": 90,
     * "quantity": 10,
     * "carriage": 0,
     * "refundable": false,
     * "barcode": "",
     * "sellnow": true,
     * "dateSelling": "2016-11-13 14:46:16",
     * "limitCount": 0,
     * "logoUrl": "http://uploads.rockcent.com//uat/product/face/201611/13144673691dcbd4d4-767a-475b-8efc-b9f9b0aa494c5243fbf2b2119313e3f2c41261380cd790238dda.jpg",
     * "logoUrls": "[\"http://uploads.rockcent.com//uat/product/face/201611/13144673691dcbd4d4-767a-475b-8efc-b9f9b0aa494c5243fbf2b2119313e3f2c41261380cd790238dda.jpg\"]",
     * "note": "111111111111",
     * "status": "SELLING",
     * "channelSalesCode": "24235345",
     * "mallId": 1,
     * "merchantId": 74,
     * "merchantName": "改名了6666",
     * "serveRate": "2.5",
     * "resellFee": 15,
     * "shareFee": 8,
     * "recommend": false
     * },
     * ...
     * ],
     * "totalCount": 9,
     * "totalPage": 1,
     * "pageNo": 0,
     * "pageSize": 10
     * }
     * }
     */
    @RequestMapping(value = Routes.CHANNEL_WXAPP_PRODUCT_LIST, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult wxapp_index(Integer pageNo, Integer pageSize, Long channelId, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (channelId == null) {
                jr.remind("渠道ID不能为空",log);
                return;
            }
//            Channel channel = channelRepository.findTop1ByAppFlagAndAppDefaultAndIsDeleteAndChannelStatus(Whether.YES,Whether.YES, Whether.NO, ChannelStatus.USING);
//            ChannelDto channel = channelRepository.queryByAppFlagAndIsDeleteAndChannelStatus(Whether.YES, Whether.NO,ChannelStatus.USING);
            Channel channel = channelRepository.findByIdAndChannelStatusAndChannelClientType(channelId,ChannelStatus.USING, ChannelClientType.WXAPP);
            if (channel == null) {
                jr.errorParam("该渠道已经停用",log);
                return;
            }
            PageResult<ProductDto> productPageResult = merchantProductRepository.getChannelProduct(channel.getId(), this.getPage(pageNo, pageSize));
            jr.setData(productPageResult);

            //新增渠道访问数
            ChannelEventDto channelEvent = new ChannelEventDto();
            channelEvent.setChannelId(channel.getId());
            channelEvent.setMallId(channel.getMallId());
            channelEvent.setMerchantId(channel.getMerchantId());
            channelEvent.setVisitIp(RequestUtils.getIpAddress(request));
            channelEvent.setVisitCustomerId(customerDto.getId());
            channelHelper.addChannelViewLog(channelEvent);
        };
        return doing.go(request, log);
    }


    /**
     *
     * @api {get} /api/v2/channel/index/info 小程序 首页渠道信息
     * @apiGroup channel
     * @apiVersion 1.0.0
     */
    @RequestMapping(value = Routes.CHANNEL_WXAPP_INDEX_CHANNEL, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult wxapp_index_channel(HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            Channel channel = channelRepository.findTop1ByAppFlagAndIsDeleteAndChannelStatus(Whether.YES, Whether.NO, ChannelStatus.USING);
            jr.setData(channel);
        };
        return doing.go(request, log);
    }
}
